package com.tarry.shop.hanlder;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.tarry.shop.common.ResultEntity;
import com.tarry.shop.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.PropertyAccessException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingErrorProcessor;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


/**
 * <p>
 *  全局异常处理器
 * </p>
 * @author TARRY
 * @since 2021-11-21
 */
@RestControllerAdvice
@Slf4j
public class ShopExceptionHandler {

    @InitBinder
    public void binder(WebDataBinder binder){
        binder.setBindingErrorProcessor(new BindingErrorProcessor() {
            @Override
            public void processMissingFieldError(String s, BindingResult bindingResult) {
                log.info("file : {}",s);
            }

            @Override
            public void processPropertyAccessException(PropertyAccessException e, BindingResult bindingResult) {
                log.info("name:{},result:{}",e.getPropertyName(),bindingResult);
            }
        });
    }

    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是ConstraintViolationException
     * @param exception
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResultEntity ConstraintViolationException(ConstraintViolationException exception){
        String message = exception.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return ResultEntity.error(message);
    }

    /**
     * 处理请求参数格式错误：处理请求参数格式错误 @RequestBody上validate失败后抛出的异常MethodArgumentNotValidException
     * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常 BindException
     * @param e
     * @return
     */
    @ExceptionHandler({BindException.class,MethodArgumentNotValidException.class})
    public ResultEntity bindException(Exception e){
        BindingResult bindingResult;
        if (e instanceof BindException) {
            bindingResult = ((BindException) e).getBindingResult();
        }else {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        }
        String msg = bindingResult.getAllErrors().stream()
                .map(error -> error.getDefaultMessage()).collect(Collectors.joining(","));
        return ResultEntity.error(msg);
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResultEntity httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException exception){
        String msg = exception.getMethod();
        return ResultEntity.error("不支持到请求方式：" + msg);
    }


    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResultEntity httpMessageNotReadableException(HttpMessageNotReadableException ex){
        Throwable cause = ex.getCause();
        AtomicReference<String> errorMsg = new AtomicReference<>("");
        if(cause instanceof HttpMessageNotReadableException){
            List<JsonMappingException.Reference> path = ((InvalidFormatException) cause).getPath();
            path.forEach( p -> {
                String fieldName = p.getFieldName();
                log.info("【{}】参数输入非法",fieldName);
                errorMsg.set(String.format("【%s】%s", fieldName, "参数输入非法"));
                if (errorMsg != null) {
                    return;
                }
            });
        }
        return ResultEntity.error(errorMsg.get());
    }

    @ExceptionHandler(BusinessException.class)
    public ResultEntity businessException(BusinessException e){
        log.error("系统业务异常", e);
        return ResultEntity.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResultEntity systemException(Exception e){
        log.error("系统异常",e);
        return ResultEntity.error("系统异常，请联系系统管理员···");
    }
}
